<template>
  <section>
    <!--工具条：高级查询，上下架-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-input v-model="searchForm.keyword" placeholder="宠物名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getPets">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="offsale">下架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd" v-if="isShow">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表展示-->
    <el-table :data="pets" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="名称" >
      </el-table-column>
      <el-table-column prop="saleprice" label="售价" >
      </el-table-column>
      <el-table-column prop="costprice" label="成本价"  >
      </el-table-column>
      <el-table-column prop="state" label="状态"  >
        <template scope="scope" >
          <span v-if="scope.row.state==0" style="color: red">下架</span>
          <span v-if="scope.row.state!=0" style="color: green">上架</span>
        </template>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间"  >
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间"  >
      </el-table-column>
      <el-table-column prop="shop.name" label="店铺"  >
      </el-table-column>
      <el-table-column prop="type.name" label="品种"  >
      </el-table-column>
      <el-table-column prop="user.username" label="用户"  >
      </el-table-column>
      <el-table-column label="操作" width="200" v-if="isShow">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条：批量删除，分页-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="searchForm.pageSize" :total="totals" :current-page="searchForm.currentPage" style="float:right;">
      </el-pagination>
    </el-col>

    <!--添加和修改的模态框-->
    <el-dialog :title="title"  :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="saleprice">
          <el-input v-model="editForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="editForm.costprice" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="宠物类型">
          <!--
            el-select：选择框
              clearable： 可清理
              value-key="id" - 如果传递的是一个对象，这个属性值必须
            el-option：选项 - 需要遍历 所以用v-for
              v-for="item in types" : 遍历所有的类型
              :key="item.id"： 指定key值，没什么用
              :label="item.name" ： 指定要显示哪一个属性的值
              :value="item.id"：指定要传递那个值
            回显机制：
              <el-option>中：value的值与<el-select>的 v-model值匹配：
              可以是对象，必须在<el-select>中加value-key属性【value-key="id"】
                表明回显数据的依据，因为对象中有很多字段，根据对象中的id进行回显
              也可以是id【常用 - 简单】
          -->
          <el-select v-model="editForm.type_id" clearable placeholder="请选择">
            <el-option v-for="item in types"
                       :label="item.name"
                       :value="item.id">
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="资源" prop="resources">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastdfs"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="简介" prop="intro">
          <quill-editor v-model="editForm.detail.intro" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor v-model="editForm.detail.adoptNotice" :options="quillOption">
          </quill-editor>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
//引入富文本编辑器
import { quillEditor } from "vue-quill-editor";
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
//富文本与fastDfs集成
import quillConfig from '../../common/js/quill-config.js'

export default {
  components: {
    quillEditor //使用富文本编辑器<quill-editor>
  },
  data() {
    return {
      //富文本集成fastDfs数据
      quillOption: quillConfig,
      //文件上传列表 - 资源resources
      fileList:[],
      petForm: {

      },
      //添加和修改模态框的标题
      title:'',
      isShow: false,
      //高级查询数据
      searchForm: {
        keyword: null,
        totals: 0,
        currentPage: 1,
        pageSize: 5
      },
      //分页查询数据
      pets: [], //分页查询列表数据
      //分页查询 - 总数量
      totals: 0,
      //分页查询 - 当前页
      pageSize: 5,
      //分页查询 - 每页显示的条数
      currentPage: 1,
      listLoading: false, //分页查询 - 列表忙等框

      //批量删除
      sels: [],//列表选中列

      //添加和修改模态框数据1
      editFormVisible: false,//模态框是否显示
      editLoading: false, //忙等框
      editFormRules: { //模态框验证规则
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      //添加和修改模态框数据2
      editForm: {
        id: null,
        name: null,
        costprice: 0,
        saleprice: 0,
        resources:null,
        //上下架时间：添加时默认为null，上架和下架时才单独修改
        //offsaletime:null,
        //onsaletime:null,
        //createtime创建时间：添加的时候要添加-默认值，创建时间不做修改
        //createtime:null,
        //添加的时候可以选，也可以修改
        type_id: null,
        //以下三个添加的时候：管理员添加不是来自于寻主消息都为null - 默认值
        //以下三个修改的时候：不能修改
        //shop_id: null,
        //user_id: null,
        //search_master_msg_id: null,
        detail:{
          intro:null,
          adoptNotice:null
        }
      },
      //加载所有的宠物类型
      types:[],
      loginInfo: null,
    }
  },
  methods: {

    //上架
    onsale(){
      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾上架不了啊....',type: 'error'});
        return;
      }
      this.$confirm('确认上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/pet/onsale',ids).then((res) => {
          this.listLoading = false;

          if(res.data.success){
            this.$message({
              message: '上架成功',
              type: 'success'
            });
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getPets();
        });
      }).catch(() => {

      });
    },

    //下架
    offsale(){

      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾下架不了啊....',type: 'error'});
        return;
      }
      this.$confirm('确认下架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/pet/offsale',ids).then((res) => {
          this.listLoading = false;

          if(res.data.success){
            this.$message({
              message: '下架成功',
              type: 'success'
            });
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getPets();
        });
      }).catch(() => {

      });
    },

    //资源图片上传成功之后的处理
    handleSuccess(response, file, fileList){
      console.log("===========")
      console.log(fileList);
      //resultObj 文件的服务器地址，放到数据库中
      //根据双向绑定 logo 就有值 1,2,3
      if(fileList!=null && fileList.length>0){
        // 如果当前的resources为null，那么将response中的数据赋值给resources
        if(this.editForm.resources == null){
          this.editForm.resources = response.data;
        } else {
          // 如果当前的resources数据不为空，那么在resources后拼接一个逗号和数据
          this.editForm.resources = this.editForm.resources + "," + response.data;
        }
      }
      console.log(this.editForm.resources)
    },

    //资源图片点击删除时的处理
    handleRemove(file, fileList) {
      console.log(file);
      console.log(fileList);
      let filePath = file.url;
      this.$http.delete("/fastdfs/?path="+filePath)
          .then(res=>{
            if(res.data.success){
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
            }else{
              this.$message({
                message: '删除失败!',
                type: 'error'
              });
            }
          })
      filePath = filePath.replace("http://47.95.117.210:8888", "");
      console.log(filePath);
      if(fileList!=null && fileList.length>0){
        // 如果resources字符串中存在删除的图片路径后一个逗号的子字符串，说明删除的图片在字符串中间，将该子字符串替换为空串
        if (this.editForm.resources.indexOf(filePath + ",") >= 0) {
          this.editForm.resources = this.editForm.resources.replace(filePath + ",", "");
        } else if (this.editForm.resources.indexOf(filePath) >= 0) {
          // 如果不满足子字符串后有逗号，但是能查询到对应的路径，表示该字符串在resources字符串末尾，直接替换为空串
          this.editForm.resources = this.editForm.resources.replace(filePath, "");
        }
      }
      console.log(this.editForm.resources);
    },

    //点击某一页的处理
    handleCurrentChange(val) {
      this.searchForm.currentPage = val;
      this.getPets();
    },

    //高级查询 + 分页查询
    getPets() {
      let para = {
        currentPage: this.searchForm.currentPage,
        pageSize: this.searchForm.pageSize,
        keyword:this.searchForm.keyword
      };
      //显示列表忙等框
      this.listLoading = true;
      //发送异步请求加载列表数据
      this.$http.post("/pet",para).then(res=>{
        this.pets=res.data.data;
        this.totals=res.data.totals;
        //关闭列表忙等框
        this.listLoading = false;
      });
    },

    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        //显示列表忙等框
        this.listLoading = true;
        //后台地址的请求
        this.$http.delete("/pet/"+row.id).then((res) => {
          //成功不成功都要让盲等框消失
          this.listLoading = false;
          if(res.data.success){//删除成功
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            // 如果当前页为最后一页，且最后一页只有一条数据的时候，删除该数据后当前页变为上一页
            if ((this.searchForm.totals - 1) % this.searchForm.pageSize == 1 && this.searchForm.currentPage == this.searchForm.totals / this.searchForm.pageSize + 1) {
              this.searchForm.currentPage = this.searchForm.currentPage - 1;
            }
            this.getPets();
          }else{
            //后台500错误，显示具体错误信息
            this.$message.error(res.data.message);
          }
        }).catch(res => {
          //主要是针对连接不上服务器啊，前端发送问题等
          this.$message.error("系统错误，请稍后重试!");
        })
      }).catch(() => {
      });
    },

    //批量获取被删除对象的id
    selsChange: function (sels) {
      this.sels = sels;
    },

    //批量删除 - 批量删除逻辑处理
    batchRemove: function () {
      //获取被删除对象的id组成的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/pet",ids).then(res=>{
          if(res.data.success){
            this.listLoading = false;
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.currentPage = 1;
            this.getPets();
          }else{
            this.listLoading = false;
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
        }).catch(res=>{
          //主要是针对连接不上服务器啊，前端发送问题等
          this.$message.error("系统错误，请稍后重试!");
        })

      }).catch(() => {
      });
    },

    //点击编辑按钮弹出模态框
    handleEdit: function (index, row) {
      //进行数据回显：将row【本省就是一个json对象  克隆 给一个空对象{}】,防止引用传递导致的数据变化
      this.editForm = Object.assign({}, row);
      //加载所有的宠物类型
      this.getTypes();
      //会显示详情
      this.$http.get("/pet/detail/"+row.id).then(result=>{
        this.editForm.detail = result.data.data;
        console.log(result.data.data);
      });
      console.log(row);
      //图片回显，先将回显的文件列表进行清空
      this.fileList = [];
      let resources =  row.resources;
      if(resources){
        let resourcesArr = resources.split(",");
        for(let i=0;i<resourcesArr.length;i++){
          this.fileList.push({url:"http://47.95.117.210:8888" + resourcesArr[i]})
        }
      }

      this.title = "编辑";
      this.editFormVisible = true;
    },

    //显示新增界面
    handleAdd: function () {
      //初始化表单字段-利用的双向绑定的特性
      this.editForm = {
        id: null,
        name: null,
        costprice: 0,
        saleprice: 0,
        //resources:null,
        //添加的时候可以选，也可以修改
        type_id: null,
        detail:{
          intro:null,
          adoptNotice:null
        }
      }

      //清空图片列表
      this.fileList = [];
      //加载所有的宠物类型
      this.getTypes();
      this.title='新增';
      //打开弹出框
      this.editFormVisible = true;
    },

    //编辑
    editSubmit: function () {
      //验证当前的表单是否符合验证规则
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //显示提交按钮忙等框
            this.editLoading = true;
            //把表单的数据组装为json
            let para = Object.assign({}, this.editForm);

            this.$http.put('/pet',para).then((res) => {
              if(res.data.success){
                this.editLoading = false;
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                //重置表单-调用现成的方法
                this.$refs['editForm'].resetFields();
                //关闭 加载框
                this.editFormVisible = false;
                //重新刷新页面数据
                this.getPets();
              }else{
                this.editLoading = false;  		//忙等框不显示
                this.editFormVisible = false; 	//隐藏对话框
                this.$message({
                  message: res.data.message,
                  type: 'error'
                });
              }
            }).catch(res => {
              alert("系统错误,请稍后重试");
            })
          });
        }
      });
    },

    //获取所有的宠物类型
    getTypes(){
      this.$http.get("/petType").then(result=>{
        this.types = result.data;
      })
    },
    getLoginInfo() {
      let loginInfo = JSON.parse(localStorage.getItem("loginInfo"));
      if (loginInfo != null) {
        this.loginInfo = loginInfo;
        console.log(this.loginInfo)
      }
    },
    show() {
      this.$http.get("/employee/byLoginInfo/" + this.loginInfo.id).then(res => {
        if (res.data.success) {
          this.isShow = true;
        }
      })
    }

  },
  mounted() {
    //当页面加载完以后。执行的方法
    this.getPets();
    this.getLoginInfo();
    this.show();
  }
}

</script>

<style scoped>

</style>